const Express = require("express");
const ResponseHelper = require("../ResponseHelper");
const router = Express.Router();
const axios = require("axios");
const archiver = require("archiver");

router.get("/downVideo", async (req, res, next) => {
  try {
    const videoInfo = JSON.parse(req.query.videosInfo);
    console.log("video total", videoInfo.length);
    // 设置响应头以表示内容类型为ZIP文件
    res.writeHead(200, {
      "Content-Type": "application/zip",
      "Content-Disposition": 'attachment; filename="videos.zip"',
    });
    // 创建一个archiver实例用于压缩
    let archive = archiver("zip", {
      zlib: { level: 9 }, // 设置压缩级别
    });
    // 将压缩输出流定向到响应对象
    archive.pipe(res);
    for (let video of videoInfo) {
      const response = await axios({
        url: video.url,
        method: "GET",
        responseType: "stream",
      });
      // 添加文件到压缩包
      archive.append(response.data, { name: `${video.name}.mp4` });
    }
    // 完成压缩
    archive.finalize();
  } catch (error) {
    ResponseHelper.sendErr(error, res);
  }
});

module.exports = router;
